package com.chuangyang.fixboxlib.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chuangyang.fixboxlib.R;


/**
 * Created by vanshu on 15/3/26 17:01.
 */
public class RatingBar extends LinearLayout {
    private static final int DEFAULT_NUMBER_STAR = 5;
    private static final int DEFAULT_RATING = 0;
    private TypedArray a;
    int rating;
    int numStar;
    Drawable starEmpty;
    Drawable starFilled;

    public RatingBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
        try {
            a = context.obtainStyledAttributes(attrs, R.styleable.RatingBar);
            numStar = a.getInt(R.styleable.RatingBar_numStars, DEFAULT_NUMBER_STAR);
            rating = a.getInt(R.styleable.RatingBar_rating, DEFAULT_RATING);
            starEmpty = a.getDrawable(R.styleable.RatingBar_starEmpty);
            starFilled = a.getDrawable(R.styleable.RatingBar_starFilled);
        } catch (Exception e) {

        } finally {
            a.recycle();
        }
    }


    private void drawStar() {
        for (int i = 0; i < rating; i++) {
            addView(addStar(starFilled));
        }
        for (int i = 0; i < numStar - rating; i++) {
            addView(addStar(starEmpty));
        }
    }

    public void setRating(int rating) {
        this.rating = rating;
        removeAllViews();
        drawStar();
    }


    private ImageView addStar(Drawable drawable) {
        ImageView imageView = new ImageView(getContext());
        imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        imageView.setBackgroundDrawable(drawable);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return imageView;
    }
}
